package com.puff.jdbc.executor;

import java.util.List;

import com.puff.framework.utils.StringUtil;
import com.puff.log.Log;
import com.puff.log.LogFactory;

public class SQLReport {
	private static final Log log = LogFactory.get(SQLReport.class);

	private static final String QUERY_ELAPSED = "Execute SQL query '{0}' elapsed {1} millis";
	private static final String QUERY_ELAPSED_WITH_PARAMATER = "Execute query elapsed {1} millis\nSQL:{0}\nParameter:{2}";
	private static final String COMMAND_ELAPSED = "Execute SQL command '{0}' elapsed {1} millis";
	private static final String COMMAND_ELAPSED_WITH_PARAMETER = "Execute command elapsed {1} millis\nSQL:{0}\nParameter:{2}";
	private static final String EXECUTE_FAILED = "Execute SQL failed: '{0}' {1}";
	private static final String EXECUTE_FAILED_WITH_PARAMETER = "Execute SQL failed: {1}\nSQL:{0}\nParameter:{2}";
	private static final String PROCEDURE_ELAPSED = "{0} success, elapsed {1} millis";
	private static final String PROCEDURE_ELAPSED_WITH_PARAMETER = "Call procedure elapsed {1} millis\n{0}\nParameter:{2}";
	private static final String PROCEDURE_FAILED = "{0} failed:  {1}";
	private static final String PROCEDURE_FAILED_WITH_PARAMETER = "{0} failed\n{1}\nParameter {2}";

	public static void query(Object[] arguments) {
		if (arguments[2] != null) {
			log.info(StringUtil.replaceArgs(QUERY_ELAPSED_WITH_PARAMATER, arguments));
		} else {
			log.info(StringUtil.replaceArgs(QUERY_ELAPSED, arguments));
		}
	}

	public static void command(Object[] arguments) {
		if (arguments[2] != null) {
			log.info(StringUtil.replaceArgs(COMMAND_ELAPSED_WITH_PARAMETER, arguments));
		} else {
			log.info(StringUtil.replaceArgs(COMMAND_ELAPSED, arguments));
		}
	}

	public static void procedure(Object[] arguments) {
		if (arguments[2] != null) {
			log.info(StringUtil.replaceArgs(PROCEDURE_ELAPSED_WITH_PARAMETER, arguments));
		} else {
			log.info(StringUtil.replaceArgs(PROCEDURE_ELAPSED, arguments));
		}
	}

	public static void callProcedureFail(Object[] arguments) {
		if (arguments[2] != null) {
			log.error(StringUtil.replaceArgs(PROCEDURE_FAILED_WITH_PARAMETER, arguments));
		} else {
			log.error(StringUtil.replaceArgs(PROCEDURE_FAILED, arguments));
		}
	}

	public static void executeFail(Object[] arguments) {
		if (arguments[2] != null) {
			log.error(StringUtil.replaceArgs(EXECUTE_FAILED_WITH_PARAMETER, arguments));
		} else {
			log.error(StringUtil.replaceArgs(EXECUTE_FAILED, arguments));
		}
	}

	public static Object handleParameter(List<Object> param) {
		if (param == null || param.size() == 0)
			return null;
		StringBuilder sb = new StringBuilder(128).append("{");
		for (int i = 0, len = param.size(); i < len; i++) {
			sb.append(param.get(i));
			if (i < len - 1) {
				sb.append(",");
			}
		}
		return sb.append("}");
	}

}
